import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_graphics_view/src/model/item_model_data.dart';
import 'package:flutter_graphics_view/src/policy/base/policy_set.dart';
import 'package:uuid/uuid.dart';

class SceneModelContext with ChangeNotifier {
  Uuid _id = Uuid();

  HashMap<String, ItemModelData> models = HashMap();

  PolicySet policySet;

  SceneModelContext(this.policySet);

  update() {
    notifyListeners();
  }

  bool itemExists(String id) {
    return models.containsKey(id);
  }

  ItemModelData getItem(String id) {
    return models[id]!;
  }

  String addItem(ItemModelData data) {
    var isExist = itemExists(data.id);
    if (isExist) {
      return data.id;
    }
    models[data.id] = data;
    notifyListeners();
    return data.id;
  }

  removeItem(String id) {
    models.remove(id);
    notifyListeners();
  }

  removeAllItems() {
    models.clear();
    notifyListeners();
  }

  HashMap<String, ItemModelData> getAllItems() {
    return models;
  }

  setItemZOrder(String id, int zOrder) {
    if (!itemExists(id)) {
      return;
    }
    getItem(id).zOrder = zOrder;
    notifyListeners();
  }

  int moveItemToTop(String id) {
    if (!itemExists(id)) {
      return -1;
    }
    int zOrderMax = getItem(id).zOrder;
    models.values.forEach((element) {
      if (element.zOrder > zOrderMax) {
        zOrderMax = element.zOrder;
      }
    });
    getItem(id).zOrder = zOrderMax + 1;
    notifyListeners();
    return zOrderMax + 1;
  }

  int moveItemToBottom(String id) {
    if (!itemExists(id)) {
      return -1;
    }
    int zOrderMin = getItem(id).zOrder;
    models.values.forEach((element) {
      if (element.zOrder < zOrderMin) {
        zOrderMin = element.zOrder;
      }
    });
    getItem(id).zOrder = zOrderMin - 1;
    notifyListeners();
    return zOrderMin - 1;
  }
}
